package com.hyt.it.ogt.pj.utils;

import com.hyt.it.ogt.pj.model.vo.ExpertTreeVo;

import java.util.ArrayList;
import java.util.List;


/**
 * 树工具类
 */
public class TreeUtil {

    public static List<ExpertTreeVo> treeToMultilevel(List<ExpertTreeVo> trees) {
        Boolean loop = true;
        while (loop) {
            loop = false;
            for (int i = trees.size() - 1; i >= 0; i--) {
                String pid = trees.get(i).getPid();
                if (pid != null) {
                    String id = trees.get(i).getId();
                    int pIndex = -1;
                    Boolean noSon = true;
                    for (int j = 0; j < trees.size(); j++) {
                        if (trees.get(j).getPid() != null && trees.get(j).getPid().equals(id)) {
                            noSon = false;
                            break;
                        }
                        if (trees.get(j).getId().equals(pid)) {
                            pIndex = j;
                        }
                    }
                    if (noSon) {
                        if (pIndex >= 0) {
                            if (trees.get(pIndex).getChildren() == null) {
                                List<ExpertTreeVo> children = new ArrayList<ExpertTreeVo>();
                                trees.get(pIndex).setChildren(children);
                            }
                            trees.get(pIndex).getChildren().add(0, trees.get(i));
                            trees.remove(i);
                        }
                    } else {
                        loop = true;
                    }
                }
            }
        }
        return trees;
    }
}
